
/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.cms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileMode;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.io.FileUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.ss.formula.functions.T;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.ResourceLoader;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.factory.TreeBuildFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.modular.cms.entity.Template;
import vip.xiaonuo.modular.cms.enums.TemplateExceptionEnum;
import vip.xiaonuo.modular.cms.mapper.TemplateMapper;
import vip.xiaonuo.modular.cms.node.CatalogBaseTreeNode;
import vip.xiaonuo.modular.cms.node.FileTreeNode;
import vip.xiaonuo.modular.cms.param.TemplateParam;
import vip.xiaonuo.modular.cms.service.TemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.sys.modular.file.result.SysFileInfoResult;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 前端模板service接口实现类
 *
 * @author liubaihan
 * @date 2022-07-01 15:25:28
 */
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {

    @Value("${cms.templatePath}")
    private String templatePath;

    @Autowired
    private SysFileInfoService sysFileInfoService;

    @Override
    public PageResult<Template> page(TemplateParam templateParam) {
        QueryWrapper<Template> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(templateParam)) {

            // 根据模板名称 查询
            if (ObjectUtil.isNotEmpty(templateParam.getTemplateName())) {
                queryWrapper.lambda().eq(Template::getTemplateName, templateParam.getTemplateName());
            }
            // 根据作者 查询
            if (ObjectUtil.isNotEmpty(templateParam.getAuthor())) {
                queryWrapper.lambda().eq(Template::getAuthor, templateParam.getAuthor());
            }
            // 根据用于寻找模板文件 查询
            if (ObjectUtil.isNotEmpty(templateParam.getFolderPath())) {
                queryWrapper.lambda().eq(Template::getFolderPath, templateParam.getFolderPath());
            }
            // 根据模板状态 查询
            if (ObjectUtil.isNotEmpty(templateParam.getStatus())) {
                queryWrapper.lambda().eq(Template::getStatus, templateParam.getStatus());
            }
            // 根据缩略图路径 查询
            if (ObjectUtil.isNotEmpty(templateParam.getImageSrc())) {
                queryWrapper.lambda().eq(Template::getImageSrc, templateParam.getImageSrc());
            }
        }

        queryWrapper.lambda().orderByAsc(Template::getStatus);
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Template> list(TemplateParam templateParam) {
        return this.list();
    }

    @Override
    public void add(TemplateParam templateParam) {
        Template template = new Template();
        BeanUtil.copyProperties(templateParam, template);
        this.save(template);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<TemplateParam> templateParamList) {
        templateParamList.forEach(templateParam -> {
            try {
                Template template = this.queryTemplate(templateParam);
                FileUtil.del(templatePath + "/" + template.getFolderPath());
                this.removeById(template.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TemplateParam templateParam) {
        Template template = this.queryTemplate(templateParam);
        BeanUtil.copyProperties(templateParam, template);
        this.updateById(template);
    }

    @Override
    public Template detail(TemplateParam templateParam) {
        return this.queryTemplate(templateParam);
    }

    /**
     * 获取前端模板
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    private Template queryTemplate(TemplateParam templateParam) {
        Template template = this.getById(templateParam.getId());
        if (ObjectUtil.isNull(template)) {
            throw new ServiceException(TemplateExceptionEnum.NOT_EXIST);
        }
        return template;
    }

    @Override
    public Boolean upload(MultipartFile file){

        boolean isExist = FileUtil.exist(templatePath);

        if(!isExist){
           FileUtil.mkdir(templatePath);
        }

        try {
            String originalFilename = file.getOriginalFilename();
            File zipFile = new File( templatePath + "/" + originalFilename);
            file.transferTo(zipFile);

            ZipUtil.unzip(zipFile,new File(templatePath));

            zipFile.delete();

            /** 数据库记录*/
            Template template = new Template();

            SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();

            // 检查是否存在封面信息
            String coverPath = templatePath + "/" + StrUtil.subBefore(originalFilename, ".", true) + "/cover.png";
            boolean existCover = FileUtil.exist(coverPath);
            if(existCover){
                // file 转 MultipartFile
                BufferedInputStream coverStream = FileUtil.getInputStream(coverPath);
                MultipartFile multipartFile = new MockMultipartFile("file", "cover.png", ContentType.APPLICATION_OCTET_STREAM.toString(), coverStream);
                Long fileId = sysFileInfoService.uploadMinIOFile(multipartFile);
                String path = "sysFileInfo/minio/preview?id=" + fileId;
                template.setImageSrc(path);
            }
            template.setAuthor(sysLoginUser.getName());
            template.setFolderPath(FileNameUtil.mainName(originalFilename));
            template.setStatus("2");
            template.setTemplateName(FileNameUtil.mainName(originalFilename));

            this.save(template);

            return true;

        }catch (Exception exception){
            exception.printStackTrace();
            return false;
        }

    }

    @Override
    public ResponseData getTreeList(String templateId) {
        Template template = this.getById(templateId);
        String path = templatePath + "\\" + template.getFolderPath();
        List<FileTreeNode> list = this.getListFileNamesByFilePath(path,template);
        return ResponseData.success(list);
    }
    
    private List<FileTreeNode> getListFileNamesByFilePath(String foldPath,Template template){

        List<File> files = FileUtil.loopFiles(foldPath);

        int fileFoldId = 2;

        List<FileTreeNode> fileTreeNodes = new ArrayList<>();
        FileTreeNode fileTreeNode = new FileTreeNode();
        fileTreeNode.setId(1L);
        fileTreeNode.setParentPath("");
        fileTreeNode.setPath(foldPath);
        fileTreeNode.setParentId(0L);
        fileTreeNode.setFileType("1");
        fileTreeNode.setFolder(true);
        fileTreeNode.setSpread(true);
        fileTreeNode.setTitle(template.getFolderPath());
        fileTreeNodes.add(fileTreeNode);

        ArrayList<String> foldList = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            String filePathInfo = file.getParent();
            foldList.add(filePathInfo);
        }


        foldList =  CollectionUtil.distinct(foldList);
        foldList.sort((a,b) -> a.length() - b.length());

        // 文件夹
        for (int i = 0; i < foldList.size(); i++) {
            String foldName = foldList.get(i);
            List<FileTreeNode> parentFoldNodes = fileTreeNodes.stream().filter(e -> e.getPath().equals(foldName)).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(parentFoldNodes)) {
                FileTreeNode parentFoldNode = parentFoldNodes.get(0);
                FileTreeNode fileFoldNode = new FileTreeNode();
                fileFoldNode.setId((long)fileFoldId++);
                fileFoldNode.setParentPath(parentFoldNode.getPath());
                fileFoldNode.setPath(foldName);
                fileFoldNode.setParentId(parentFoldNode.getId());
                fileFoldNode.setFileType("1");
                fileTreeNodes.add(fileFoldNode);
            } else {
                String parentName = StrUtil.subBefore(foldName, "\\", true);
                List<FileTreeNode> parentFoldNodesList = fileTreeNodes.stream().filter(e -> e.getPath().equals(parentName)).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(parentFoldNodesList)) {
                    FileTreeNode parentFoldNode = parentFoldNodesList.get(0);
                    FileTreeNode fileFoldNode = new FileTreeNode();
                    fileFoldNode.setId((long) fileFoldId++);
                    fileFoldNode.setParentPath(parentName);
                    fileFoldNode.setPath(foldName);
                    fileFoldNode.setParentId(parentFoldNode.getId());
                    fileFoldNode.setFileType("1");
                    fileTreeNodes.add(fileFoldNode);
                }
            }
        }

        //fileTreeNodes = fileTreeNodes.stream().filter(e -> e.getParentId()!=0L).collect(Collectors.toList());
        // 文件
        for (int i = 0; i < files.size(); i++) {
            String foldName = files.get(i).getPath();
            List<FileTreeNode> parentFoldNodes = fileTreeNodes.stream().filter(e -> e.getPath().equals(foldName)).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(parentFoldNodes)) {
                FileTreeNode parentFoldNode = parentFoldNodes.get(0);
                FileTreeNode fileFoldNode = new FileTreeNode();
                fileFoldNode.setId((long)fileFoldId++);
                fileFoldNode.setParentPath(parentFoldNode.getPath());
                fileFoldNode.setPath(foldName);
                fileFoldNode.setParentId(parentFoldNode.getId());
                fileFoldNode.setFileType("2");
                fileTreeNodes.add(fileFoldNode);
            } else {
                String parentName = StrUtil.subBefore(foldName, "\\", true);
                List<FileTreeNode> parentFoldNodesList = fileTreeNodes.stream().filter(e -> e.getPath().equals(parentName)).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(parentFoldNodesList)) {
                    FileTreeNode parentFoldNode = parentFoldNodesList.get(0);
                    FileTreeNode fileFoldNode = new FileTreeNode();
                    fileFoldNode.setId((long) fileFoldId++);
                    fileFoldNode.setParentPath(parentName);
                    fileFoldNode.setPath(foldName);
                    fileFoldNode.setParentId(parentFoldNode.getId());
                    fileFoldNode.setFileType("2");
                    fileTreeNodes.add(fileFoldNode);
                }
            }
        }

        fileTreeNodes.forEach(e -> {
            if(e.getFileType().equals("1")){
                e.setSpread(true);
                e.setFolder(true);
            }else {
                e.setSpread(false);
                e.setFolder(false);
            }
            e.setTitle(FileUtil.getName(e.getPath()));
            e.setPath("/"+ template.getFolderPath() + "/" + StrUtil.subAfter(e.getPath(),foldPath+"\\",true).replaceAll("\\\\","/"));

        });

        return new TreeBuildFactory<FileTreeNode>().doTreeBuild(fileTreeNodes);
    }



    public static void main(String[] args) {
//        String filePath = "D:\\cms_template\\moban1";
//        List<File> files = FileUtil.loopFiles(filePath);
//
//        int fileFoldId = 2;
//
//        List<FileTreeNode> fileTreeNodes = new ArrayList<>();
//        FileTreeNode fileTreeNode = new FileTreeNode();
//        fileTreeNode.setId(1L);
//        fileTreeNode.setParentPath("");
//        fileTreeNode.setPath(filePath);
//        fileTreeNode.setParentId(0L);
//        fileTreeNode.setFileType("1");
//        fileTreeNodes.add(fileTreeNode);
//
//        ArrayList<String> foldList = new ArrayList<>();
//        for (int i = 0; i < files.size(); i++) {
//            File file = files.get(i);
//            String filePathInfo = file.getParent();
//            foldList.add(filePathInfo);
//        }
//
//
//        foldList =  CollectionUtil.distinct(foldList);
//        foldList.sort((a,b) -> a.length() - b.length());
//
//        // 文件夹
//        for (int i = 0; i < foldList.size(); i++) {
//            String foldName = foldList.get(i);
//            List<FileTreeNode> parentFoldNodes = fileTreeNodes.stream().filter(e -> e.getPath().equals(foldName)).collect(Collectors.toList());
//            if(CollectionUtil.isNotEmpty(parentFoldNodes)) {
//                FileTreeNode parentFoldNode = parentFoldNodes.get(0);
//                FileTreeNode fileFoldNode = new FileTreeNode();
//                fileFoldNode.setId((long)fileFoldId++);
//                fileFoldNode.setParentPath(parentFoldNode.getPath());
//                fileFoldNode.setPath(foldName);
//                fileFoldNode.setParentId(parentFoldNode.getId());
//                fileFoldNode.setFileType("1");
//                fileTreeNodes.add(fileFoldNode);
//            } else {
//                String parentName = StrUtil.subBefore(foldName, "\\", true);
//                List<FileTreeNode> parentFoldNodesList = fileTreeNodes.stream().filter(e -> e.getPath().equals(parentName)).collect(Collectors.toList());
//                if(CollectionUtil.isNotEmpty(parentFoldNodesList)) {
//                    FileTreeNode parentFoldNode = parentFoldNodesList.get(0);
//                    FileTreeNode fileFoldNode = new FileTreeNode();
//                    fileFoldNode.setId((long) fileFoldId++);
//                    fileFoldNode.setParentPath(parentName);
//                    fileFoldNode.setPath(foldName);
//                    fileFoldNode.setParentId(parentFoldNode.getId());
//                    fileFoldNode.setFileType("1");
//                    fileTreeNodes.add(fileFoldNode);
//                }
//            }
//        }
//
//        // 文件
//        for (int i = 0; i < files.size(); i++) {
//            String foldName = files.get(i).getPath();
//            List<FileTreeNode> parentFoldNodes = fileTreeNodes.stream().filter(e -> e.getPath().equals(foldName)).collect(Collectors.toList());
//            if(CollectionUtil.isNotEmpty(parentFoldNodes)) {
//                FileTreeNode parentFoldNode = parentFoldNodes.get(0);
//                FileTreeNode fileFoldNode = new FileTreeNode();
//                fileFoldNode.setId((long)fileFoldId++);
//                fileFoldNode.setParentPath(parentFoldNode.getPath());
//                fileFoldNode.setPath(foldName);
//                fileFoldNode.setParentId(parentFoldNode.getId());
//                fileFoldNode.setFileType("1");
//                fileTreeNodes.add(fileFoldNode);
//            } else {
//                String parentName = StrUtil.subBefore(foldName, "\\", true);
//                List<FileTreeNode> parentFoldNodesList = fileTreeNodes.stream().filter(e -> e.getPath().equals(parentName)).collect(Collectors.toList());
//                if(CollectionUtil.isNotEmpty(parentFoldNodesList)) {
//                    FileTreeNode parentFoldNode = parentFoldNodesList.get(0);
//                    FileTreeNode fileFoldNode = new FileTreeNode();
//                    fileFoldNode.setId((long) fileFoldId++);
//                    fileFoldNode.setParentPath(parentName);
//                    fileFoldNode.setPath(foldName);
//                    fileFoldNode.setParentId(parentFoldNode.getId());
//                    fileFoldNode.setFileType("1");
//                    fileTreeNodes.add(fileFoldNode);
//                }
//            }
//        }
//
//        List<FileTreeNode> fileTreeNodeList = new TreeBuildFactory<FileTreeNode>().doTreeBuild(fileTreeNodes);、

        String s = "D:/cms_template/_moban1/js/owl.carousel.min.js";
        String name = StrUtil.replace(s,"/","\\");
        System.out.println(name);
        //List<FileTreeNode> list = new TemplateServiceImpl().getListFileNamesByFilePath(s,template);
    }
}
